const Router = require('koa-router')
const db = require('../db')

const router = new Router({ prefix: '/api/points' })

// 获取积分概览
router.get('/overview', async (ctx) => {
  try {
    // 从请求参数中获取用户ID，如果未提供则默认为1（用于开发测试）
    const userId = ctx.query.userId || 1;
    
    const [earnResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "earn"',
      [userId]
    )
    
    const [spendResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "spend"',
      [userId]
    )

    const totalPoints = Number(earnResults.total || 0)
    const usedPoints = Number(spendResults.total || 0)
    const availablePoints = totalPoints - usedPoints

    ctx.body = {
      code: 200,
      data: {
        totalPoints,
        availablePoints,
        usedPoints
      }
    }
  } catch (error) {
    console.error('获取积分概览失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 获取积分历史记录
router.get('/history', async (ctx) => {
  try {
    // 从请求参数中获取用户ID，如果未提供则默认为1（用于开发测试）
    const userId = ctx.query.userId || 1;
    
    const records = await db.query(`
      SELECT 
        id,
        amount,
        type,
        title,
        DATE_FORMAT(created_at, '%Y-%m-%d %H:%i') as date
      FROM points_history 
      WHERE user_id = ?
      ORDER BY created_at DESC
    `, [userId])

    ctx.body = { code: 200, data: records }
  } catch (error) {
    console.error('获取积分历史失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

module.exports = router